<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改入库信息')" />
    <th:block th:include="include :: datetimepicker-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-inorder-edit" th:object="${outOrderVo.outOrder}">
            <input name="id" th:value="${outOrderVo.outOrder.id}" type="hidden">
            <input name="status" th:value="0" type="hidden">
            <h4 class="form-header h4">出库信息</h4>
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">出库单编号：</label>
                <div class="col-sm-8">
                    <input name="orderCode" th:value="${outOrderVo.outOrder.orderCode}" class="form-control" type="text" required readonly>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">出库类型：</label>
                <div class="col-sm-8">
                    <select id="orderType" name="orderType" class="form-control m-b" th:with="type=${@dict.getType('out_order_type')}" required disabled>
                        <option value="">请选择</option>
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:field="*{orderType}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label ">订单号：</label>
                <div class="col-sm-8">
                    <input name="orderName" th:value="${outOrderVo.outOrder.orderName}" class="form-control" type="text">
                </div>
            </div>
            <!--<div class="form-group" id="showSaleOrder" th:if="${not #strings.isEmpty(outOrderVo.outOrder.sourceOrderCode)}">-->
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">来源订单：</label>
                <div class="col-sm-8">
                    <div class="input-group">
                        <input id="sourceOrderId" name="sourceOrderId" type="hidden" th:value="${outOrderVo.outOrder.sourceOrderId}">
                        <input id="sourceOrderCode" name="sourceOrderCode" class="form-control" type="text" onclick="selectSaleOrder()" th:value="${outOrderVo.outOrder.sourceOrderCode}" readonly required>
                        <span class="input-group-addon"><i class="fa fa-search"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">出库日期：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input name="orderDate" th:value="${#dates.format(outOrderVo.outOrder.orderDate, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text" required>
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">客户：</label>
                <div class="col-sm-8">
                    <div class="input-group">
                        <input id="customerId" name="customerId" type="hidden" th:value="${outOrderVo.outOrder.customerId}">
                        <input id="customerName" name="customerName" class="form-control" type="text" onclick="selectCustomer()" th:value="${outOrderVo.outOrder.customerName}" required>
                        <span class="input-group-addon"><i class="fa fa-search"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">出库仓库：</label>
                <div class="col-sm-8">
                    <div class="input-group">
                        <input id="warehouseId" name="warehouseId" type="hidden" th:value="${outOrderVo.outOrder.warehouseId}">
                        <input id="warehouseName" name="warehouseName" class="form-control" type="text" onclick="selectWarehouse()" th:value="${outOrderVo.outOrder.warehouseName}" readonly>
                        <span class="input-group-addon"><i class="fa fa-search"></i></span>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label">承运商：</label>
                <div class="col-sm-8">
                    <div class="input-group">
                        <input id="carriersId" name="carriersId" type="hidden" th:value="${outOrderVo.outOrder.carriersId}">
                        <input id="carriersName" name="carriersName" class="form-control" type="text" onclick="selectCarriers()" th:value="${outOrderVo.outOrder.carriersName}" required>
                        <span class="input-group-addon"><i class="fa fa-search"></i></span>
                    </div>
                </div>
            </div>


            <div class="form-group">
                <label class="col-sm-3 control-label">备注：</label>
                <div class="col-sm-8">
                    <textarea name="remark" class="form-control" maxlength="200">[[${outOrderVo.outOrder.remark}]]</textarea>
                </div>
            </div>

            <h4 class="form-header h4">商品数据</h4>
            <div class="row">
                <div class="col-sm-12">
                    <!--<button type="button" class="btn btn-white btn-sm" onclick="addColumn()"><i class="fa fa-plus"> 增加</i></button>-->
                    <button type="button" class="btn btn-white btn-sm" onclick="sub.delRow()"><i class="fa fa-minus"> 删除</i></button>
                    <div class="col-sm-12 select-table table-striped">
                        <table id="bootstrap-table"></table>
                    </div>
                </div>
            </div>
        </form>

        <div class="row">
            <div class="col-sm-offset-5 col-sm-10">
                <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存</button>&nbsp;
                <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭 </button>
            </div>
        </div>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <script th:inline="javascript">
        var prefix = ctx + "store/outorder";
        var goodsUnitDatas = [[${@dict.getType('product_unit')}]];//商品单位
        var warehouseIdDatas = [[${outOrderVo.outOrder.warehouseId}]];//商品单位

        $("#form-inorder-edit").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                $.operate.saveTab(prefix + "/edit", $('#form-inorder-edit').serialize());
            }
        }

        $("input[name='orderDate']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        function selectOrderInfo(){
            var orderType = $("#orderType").val();
            console.info("======="+orderType+"====")
            if(orderType==""){
                $.modal.alertWarning("请先选择【出库类型】");
            }else{
                if(orderType=="1"){//领料出库
                    selectProductOrder()
                }
                if(orderType=="2"){//销售出库
                    selectSaleOrder();
                }
            }
        }


        /* 选择生产订单 */
        var productPrefix = ctx + "order/productorder"
        function selectProductOrder() {
            var url = productPrefix + '/selectProductOrder';
            var options = {
                title: '选择生产订单',
                url: url,
                callBack: doSubmitProductOrder
            };
            $.modal.openOptions(options);
        }

        function doSubmitProductOrder(index, layero){
            var iframeWin = layero.find("iframe")[0].contentWindow.$.table;
            var rows = iframeWin.selectFirstColumns();//调用子页面的方法 获取ID
            if (rows.length == 0) {
                $.modal.alertWarning("请至少选择一条记录");
                return;
            }
            var id = rows.join();
            $('#sourceOrderId').val(id);
            var orderNo=iframeWin.selectColumns("orderNo").join();//调用子页面的方法 获取ID
            $('#sourceOrderNo').val(orderNo);

            var customerId=iframeWin.selectColumns("customerId").join();//调用子页面的方法 获取ID
            $('#customerId').val(customerId)
            var customerName=iframeWin.selectColumns("customerName").join();//调用子页面的方法 获取ID
            $('#customerName').val(customerName)

            //获取仓库信息
            var warehouseId = $("#warehouseId").val();
            if(warehouseId != "") {
                var orderType = $("#orderType").val();
                //填充子表
                fillOutOrderItem(orderType, id, warehouseId)
            }


            $.modal.close(index);
        }

        /* 选择销售单 */
        var saleOrderPrefix = ctx + "order/saleorder"
        function selectSaleOrder() {
            var url = saleOrderPrefix + '/selectSaleOrder';
            var options = {
                title: '选择销售订单',
                url: url,
                callBack: doSubmitSaleOrder
            };
            $.modal.openOptions(options);
        }

        function doSubmitSaleOrder(index, layero){
            var iframeWin = layero.find("iframe")[0].contentWindow.$.table;
            var rows = iframeWin.selectFirstColumns();//调用子页面的方法 获取ID
            if (rows.length == 0) {
                $.modal.alertWarning("请至少选择一条记录");
                return;
            }
            $('#sourceOrderId').val(rows.join())
            var orderCode=iframeWin.selectColumns("orderCode").join();//调用子页面的方法 获取ID
            $('#sourceOrderCode').val(orderCode)

            var customerId=iframeWin.selectColumns("customerId").join();//调用子页面的方法 获取ID
            $('#customerId').val(customerId)
            var customerName=iframeWin.selectColumns("customerName").join();//调用子页面的方法 获取ID
            $('#customerName').val(customerName)

            //获取仓库信息
            var warehouseId = $("#warehouseId").val();
            if(warehouseId != "") {
                var orderType = $("#orderType").val();
                //填充子表
                fillOutOrderItem(orderType, rows.join(), warehouseId)
            }

            $.modal.close(index);
        }

        //填充出库单子表信息
        function fillOutOrderItem(orderType, orderId, warehouseId) {
            //重置子表
            sub.removeAllRow();
            var data = {"orderType": orderType,"sourceOrderId":orderId,"warehouseId":warehouseId};
            var config = {
                url: prefix + "/item/ajaxList",
                type: "post",
                dataType: "json",
                data: data,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍后...");
                },
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.each(result.data,function(index,value){
                            var row = {
                                id: "",
                                goodsId: value.goodsId,
                                goodsCode: value.goodsCode,
                                goodsName: value.goodsName,
                                goodsUnit: value.goodsUnit,
                                goodsUnitDesc:value.goodsUnitDesc,
                                stockNumber: value.stockNumber,
                                planNumber: value.planNumber,
                                actualNumber: value.actualNumber,
                                packageNumber: "",
                                packageUnit: "",
                                remark: ""
                            }
                            sub.addRow(row);
                        });
                    } else {
                        $.modal.alertError(result.msg);
                    }
                    $.modal.closeLoading();
                }

            };
            $.ajax(config);
        };

        //初始化
        $(function() {
            var data = [[${outOrderVo.items}]];
            init(data);
        });

        function init(data) {
            // 初始化数据, 可以由后台传过来
            var options = {
                data: data,
                pagination: false,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                columns: [{
                    checkbox: true
                },
                    {
                        field: 'index',
                        align: 'center',
                        title: "序号",
                        formatter: function (value, row, index) {
                            var columnIndex = $.common.sprintf("<input type='hidden' name='index' value='%s'>", $.table.serialNumber(index));
                            var id = $.common.sprintf("<input type='hidden' name='items[%s].id' value='%s' readonly>", index, row.id);
                            return columnIndex + $.table.serialNumber(index)+id;
                        }
                    },
                    {
                        field: 'id',
                        align: 'center',
                        title: 'id',
                        visible: false
                    },
                    {
                        field: 'batchNo',
                        align: 'center',
                        title: '批次',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' name='items[%s].batchNo' value='%s' readonly>", index, value);
                            return html;
                        }
                    },
                    {
                        field: 'goodsName',
                        align: 'center',
                        title: '商品名称',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' name='items[%s].goodsName' value='%s' readonly>", index, value);
                            var goodsId = $.common.sprintf("<input type='hidden' name='items[%s].goodsId' value='%s'>", index, row.goodsId);//商品id 隐藏域
                            var goodsCode = $.common.sprintf("<input type='hidden' name='items[%s].goodsCode' value='%s'>", index, row.goodsCode);//商品code 隐藏域
                            return html+goodsId+goodsCode;
                        },
                        //events: onclickEvent
                    },
                    {
                        field: 'stockNumber',
                        align: 'center',
                        title: '库存数量',
                        formatter: function(value, row, index) {
                            var html = '<input class="form-control" type="number" step="0.01" name="items['+index+'].stockNumber" value="'+value+'" maxlength="10" readonly >';
                            return html;
                        },
                    },
                    {
                        field: 'planNumber',
                        align: 'center',
                        title: '订单数量',
                        formatter: function(value, row, index) {
                            var html = '<input class="form-control" type="number" step="0.01" name="items['+index+'].planNumber" value="'+value+'" maxlength="10"  readonly>';
                            return html;
                        },
                    },
                    {
                        field: 'actualNumber',
                        align: 'center',
                        title: '出库数量',
                        formatter: function(value, row, index) {
                            var html = '<input class="form-control" type="number" step="0.01" name="items['+index+'].actualNumber" value="'+value+'" onchange="compareInfo('+index+','+row.planNumber+',this)" maxlength="10"  required>';
                            return html;
                        },
                    },
                    {
                        field: 'goodsUnitDesc',
                        align: 'center',
                        title: '单位',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' name='items[%s].goodsUnitDesc' value='%s' readonly>", index, value);
                            var goodsUnit = $.common.sprintf("<input type='hidden' name='items[%s].goodsUnit' value='%s'>", index, row.goodsUnit);//商品unit
                            return html+goodsUnit;
                        }
                    },
                    {
                        field: 'packageNumber',
                        align: 'center',
                        title: '包装数量',
                        formatter: function(value, row, index) {
                            var html = '<input class="form-control" type="number" name="items['+index+'].packageNumber" value="'+value+'" maxlength="6" >';
                            return html;
                        },
                    },
                    {
                        field: 'packageUnit',
                        align: 'center',
                        title: '包装规格',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' name='items[%s].packageUnit' value='%s' >", index, value);
                            return html;
                        }
                    },
                    {
                        field: 'remark',
                        align: 'center',
                        title: '要求',
                        formatter: function(value, row, index) {
                            var html = '<textarea class="form-control"  name="items['+index+'].remark" maxlength="200">'+value+'</textarea>';
                            return html;
                        }
                    }
                ]
            };
            $.table.init(options);
        };

        //新增table行
        function addColumn() {
            var row = {
                id: "",
                goodsId: "",
                goodsName: "",
                goodsUnit: "",
                goodsUnitDesc:"",
                planNumber: "",
                batchNo: "",
                packageNumber: "",
                packageUnit: "",
            }
            sub.addRow(row);
        }

        /* 选择客户 */
        var customerPrefix = ctx + "basic/customer"
        function selectCustomer() {
            var url = customerPrefix + '/selectCustomer';
            var options = {
                title: '选择客户',
                url: url,
                callBack: doSubmitCustomer
            };
            $.modal.openOptions(options);
        }

        function doSubmitCustomer(index, layero){
            var iframeWin = layero.find("iframe")[0].contentWindow.$.table;
            var rows = iframeWin.selectFirstColumns();//调用子页面的方法 获取ID
            if (rows.length == 0) {
                $.modal.alertWarning("请至少选择一条记录");
                return;
            }
            $('#customerId').val(rows.join())
            var customerName=iframeWin.selectColumns("customerName").join();//调用子页面的方法 获取ID
            $('#customerName').val(customerName)

            $.modal.close(index);
        }

        /* 选择仓库 */
        var warehousePrefix = ctx + "basic/warehouse"
        function selectWarehouse() {
            var url = warehousePrefix + '/selectWarehouse';
            var options = {
                title: '选择仓库',
                url: url,
                callBack: doSubmitWarehouse
            };
            $.modal.openOptions(options);
        }

        function doSubmitWarehouse(index, layero){
            var iframeWin = layero.find("iframe")[0].contentWindow.$.table;
            var rows = iframeWin.selectFirstColumns();//调用子页面的方法 获取ID
            if (rows.length == 0) {
                $.modal.alertWarning("请至少选择一条记录");
                return;
            }
            $('#warehouseId').val(rows.join())
            var warehouseName=iframeWin.selectColumns("warehouseName").join();
            $('#warehouseName').val(warehouseName)

            //重置子表信息
            //reset($('#warehouseId').val());
            //仓库变动，数据重置
            var sourceOrderId = $('#sourceOrderId').val();
            if(sourceOrderId != "") {
                var orderType = $("#orderType").val();
                //填充子表
                fillOutOrderItem(orderType, sourceOrderId, rows.join())
            }

            $.modal.close(index);
        }

        /* 选择承运商 */
        var carriersPrefix = ctx + "basic/carriers"
        function selectCarriers() {
            var url = carriersPrefix + '/selectCarriers';
            var options = {
                title: '选择承运商',
                url: url,
                callBack: doSubmitCarriers
            };
            $.modal.openOptions(options);
        }

        function doSubmitCarriers(index, layero){
            var iframeWin = layero.find("iframe")[0].contentWindow.$.table;
            var rows = iframeWin.selectFirstColumns();//调用子页面的方法 获取ID
            if (rows.length == 0) {
                $.modal.alertWarning("请至少选择一条记录");
                return;
            }
            $('#carriersId').val(rows.join())
            var carriersName=iframeWin.selectColumns("carriersName").join();
            $('#carriersName').val(carriersName)

            $.modal.close(index);
        }


        /**
         * 比较订单数量
         * */
        function compareInfo(index, number, obj) {
            if ($.common.isNotEmpty(index) && $.common.isNotEmpty(number)) {
                var actual = $(obj).val();
                var regu = /^\d+(\.{0,1}\d{1,2})?$/;//非负浮点数（正浮点数 + 0）
                if ($.common.isEmpty(actual) || !regu.test(actual)) {
                    $.modal.alertWarning("不能为空或输入的不是非负浮点数(只能保留2位)");
                    return;
                }
                if(parseFloat(actual)>parseFloat(number)){
                    $.modal.alertWarning("出库数量不能超过订单数量");
                    actual=number;
                }
                updateCell(index, actual);//修改值
            }
        }

        //更新指定的列数据
        function updateCell(index, planNumberVal) {//更新表格数据
            var _data = new Object();//某行数据
            _data.actualNumber = planNumberVal;
            $("#" + table.options.id).bootstrapTable("updateRow", {index: index, row: _data});
        }



        /* 选择库存商品 */
        var stockPrefix = ctx + "store/stock"
        function  selectShopGoods(warehouseId) {// index:所在行的索引
            var url = stockPrefix + '/selectStock?warehouseId='+warehouseId;
            var options = {
                title: '选择商品',
                url: url,
                callBack: doSubmitStock
            };
            $.modal.openOptions(options);
        }
        var orderSeedId;//子表ID
        function doSubmitStock(index, layero){
            var iframeWin = layero.find("iframe")[0].contentWindow.$.table;
            var rows = iframeWin.selectFirstColumns();//调用子页面的方法 获取ID
            if (rows.length == 0) {
                $.modal.alertWarning("请至少选择一条记录");
                return;
            }

            var goodsId=iframeWin.selectColumns("goodsId").join();//调用子页面的方法 获取ID
            var goodsCode=iframeWin.selectColumns("goodsCode").join();
            var goodsName=iframeWin.selectColumns("goodsName").join();
            var goodsUnit=iframeWin.selectColumns("goodsUnit").join();
            var planNumber=iframeWin.selectColumns("stockNumber").join();
            var batchNo=iframeWin.selectColumns("batchNo").join();
            var goodsUnitDesc = "";//单位描述
            $.each(goodsUnitDatas,function(index,obj){  //index:索引obj:循环的每个元素
                if(obj.dictValue == goodsUnit){
                    goodsUnitDesc= obj.dictLabel;
                }
            });
            var data = $("#" + table.options.id).bootstrapTable('getData');
            var flag=0;
            $.each(data,function(index,obj) {  //index:索引obj:循环的每个元素
                if(obj.goodsId ==  goodsId){
                    flag=1;
                    return false; //跳出循环
                }
            });
            if(flag == 1){$.modal.alertWarning("商品已在清单中!"); return;}

            $.modal.close(index);


            var _data = new Object();//某行数据
            _data.goodsId = goodsId;
            _data.batchNo = batchNo;
            _data.goodsCode = goodsCode;
            _data.goodsName = goodsName;
            _data.goodsUnit = goodsUnit;
            _data.goodsUnitDesc = goodsUnitDesc;
            _data.planNumber = planNumber;
            //_data.id = orderSeedId;
            $("#" + table.options.id).bootstrapTable("updateRow",{index : orderSeedId,row : _data});

        }


        /**
         * 选中商品事件
         * */
        window.onclickEvent = {
            'click .form-control': function (e, value, row, index) {
                var warehouseId = $('#warehouseId').val();
                if (warehouseId == '' ) {
                    $.modal.alertWarning("请先选择出库仓库");
                    return;
                }
                orderSeedId = index;
                selectShopGoods(warehouseId);
            }
        };
    </script>
</body>
</html>